@echo off
chcp 65001 >nul 2>&1
setlocal enabledelayedexpansion

echo.
echo ===============================================================================
echo                        MCP代码生成系统 v2.0
echo                         服务停止脚本 (Windows)
echo ===============================================================================
echo.

echo [停止] 正在停止所有服务...
echo.

:: 定义服务端口和名称
set "services=8000:Generated_MCP_Server 8010:MCP_Generator 8011:MCP_Server_Manager 8080:Agent_Client 8090:Web_Frontend"

:: 停止服务进程
for %%s in (%services%) do (
    for /f "tokens=1,2 delims=:" %%a in ("%%s") do (
        echo [停止] 正在停止 %%b (端口: %%a^)...
        
        :: 查找并终止占用端口的进程
        for /f "tokens=5" %%p in ('netstat -ano ^| findstr ":%%a "') do (
            if "%%p" neq "" (
                taskkill /PID %%p /F >nul 2>&1
                if not errorlevel 1 (
                    echo [OK] %%b 已停止 (PID: %%p^)
                )
            )
        )
    )
)

:: 停止相关的Python和uvicorn进程
echo.
echo [清理] 清理相关进程...

:: 清理 MCP 相关进程
wmic process where "commandline like '%%mcp%%' and name='python.exe'" delete >nul 2>&1
wmic process where "commandline like '%%agent_client%%' and name='python.exe'" delete >nul 2>&1
wmic process where "commandline like '%%uvicorn%%' and name='python.exe'" delete >nul 2>&1

:: 强制清理所有 Python 进程（谨慎使用）
taskkill /F /IM python.exe >nul 2>&1
taskkill /F /IM uvicorn.exe >nul 2>&1

:: 清理 PID 文件
if exist logs\*.pid (
    del /F /Q logs\*.pid >nul 2>&1
    echo [OK] PID 文件已清理
)

:: 等待进程完全停止
timeout /t 3 >nul

:: 验证服务是否已停止
echo.
echo [验证] 验证服务停止状态...
set "running_services="
for %%s in (%services%) do (
    for /f "tokens=1,2 delims=:" %%a in ("%%s") do (
        netstat -an | findstr ":%%a " | findstr "LISTENING" >nul 2>&1
        if not errorlevel 1 (
            echo [警告] %%b 仍在运行 (端口: %%a^)
            set "running_services=!running_services! %%b"
        ) else (
            echo [OK] %%b 已停止 (端口: %%a^)
        )
    )
)

echo.
if defined running_services (
    echo [警告] 以下服务仍在运行: !running_services!
    echo [提示] 请手动检查或重启系统
) else (
    echo [完成] 所有服务已成功停止！
)

:: 清理缓存文件
echo.
echo [清理] 清理Python缓存文件...
for /d /r %%d in (__pycache__) do @if exist "%%d" rd /s /q "%%d" 2>nul
del /s /q *.pyc >nul 2>&1
echo [OK] 缓存文件已清理

echo.
echo [日志] 服务日志保存在 logs\ 目录中
echo [提示] 清理所有日志: del /F /Q logs\*.log
echo [提示] 如需完全重置，请运行: scripts\reset.bat
echo.
pause
